package com.nbsaas.boot.controller.web;

import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.nbsaas.boot.pay.ext.apis.PaymentExtApi;
import com.nbsaas.boot.pay.ext.apis.PaymentHandleApi;
import com.nbsaas.boot.rest.response.MapResponse;
import jodd.io.IOUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;

@RestController
public class PayNotifyController implements InitializingBean, DisposableBean {


    private Logger logger= LoggerFactory.getLogger("site");

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("init site");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("destroy site");
    }

    @Autowired
    private PaymentHandleApi paymentHandleApi;



    @RequestMapping("/weiXinNotifyUrl")
    public MapResponse weiXinNotifyUrl(HttpServletRequest request) {
        MapResponse result=new MapResponse();

        try {
            ServletInputStream stream = request.getInputStream();
            byte[] data = IOUtil.readBytes(stream);
            String msg = new String(data);


            WxPayOrderNotifyResult notifyResult = WxPayOrderNotifyResult.fromXML(msg);
            if ( "SUCCESS".equals(notifyResult.getReturnCode())) {
                paymentHandleApi.handle(notifyResult);
                result.put("return_code","SUCCESS");
                result.put("return_msg","OK");

            } else {
                result.put("return_code","FAIL");
                result.put("return_msg","OK");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("return_code","FAIL");
            result.put("return_msg","OK");
        }
        return result;
    }
}
